<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import webRTCService from '../services/webrtc';

interface Props {
  roomId: string;
  userId: string;
}

const props = defineProps<Props>();
console.log('props', props)
const emit = defineEmits<{
  'leave-room': []
}>();

const localVideoRef = ref<HTMLVideoElement | null>(null);
const remoteStreams = ref<Record<string, MediaStream>>({});  // 远程视频流映射 userId -> stream
const connectionStatus = ref<string>('正在连接...');
const isMuted = ref<boolean>(false);
const isVideoOff = ref<boolean>(false);
const errorMessage = ref<string>('');
const roomLink = ref<string>('');
const roomUsers = ref<string[]>([]);  // 房间内其他用户列表
const debugInfo = ref<string>(''); // 调试信息

// 计算所有用户（包括本地用户）
const allUsers = computed<string[]>(() => {
  // 创建集合以确保唯一性
  console.log('当前用户:', props.userId, '房间用户:', roomUsers.value);
  const uniqueUsers = [...new Set([props.userId, ...roomUsers.value])];
  console.log('计算得到的所有用户:', uniqueUsers);
  return uniqueUsers;
});

// 使用手动更新方法确保Vue的响应式更新
function updateRoomUsers(userIds: string[]): void {
  console.log('手动更新房间用户列表:', userIds);

  // 过滤掉自己的ID，因为不需要在用户列表中看到自己两次
  const filteredIds = userIds.filter(id => id !== props.userId);

  // 清空再设置，确保响应式更新
  roomUsers.value = [];

  // 使用nextTick确保DOM更新后再设置新值
  nextTick(() => {
    roomUsers.value = filteredIds;
    console.log('更新后的房间用户列表:', roomUsers.value);
  });
}

// 更新远程流
function updateRemoteStream(userId: string, stream: MediaStream): void {
  console.log('更新远程流:', userId);
  // 使用新对象替换旧对象，确保Vue检测到变化
  const newStreams = { ...remoteStreams.value };
  newStreams[userId] = stream;
  remoteStreams.value = newStreams;

  // 确保该用户也在用户列表中
  if (!roomUsers.value.includes(userId) && userId !== props.userId) {
    updateRoomUsers([...roomUsers.value, userId]);
  }
}

// 移除远程流
function removeRemoteStream(userId: string): void {
  console.log('移除远程流:', userId);
  if (remoteStreams.value[userId]) {
    const newStreams = { ...remoteStreams.value };
    delete newStreams[userId];
    remoteStreams.value = newStreams;
  }
}

// 跟踪视频加载状态
const videoLoadingStates = ref<Record<string, string>>({});
const localVideoLoading = ref<boolean>(true);

// 更新视频加载状态
function updateVideoLoadingState(userId: string, state: string): void {
  const newStates = { ...videoLoadingStates.value };
  newStates[userId] = state;
  videoLoadingStates.value = newStates;
  console.log(`视频 ${userId} 状态更新为: ${state}`);
}

// 初始化WebRTC
async function initializeWebRTC(): Promise<void> {
  try {
    debugInfo.value = '正在初始化WebRTC...';

    // 1. 连接信令服务器
    webRTCService.connect();

    // 设置连接成功事件监听器
    webRTCService.on('connection-established', () => {
      console.log('信令服务器连接已建立');
      connectionStatus.value = '已连接';
      debugInfo.value += '\n信令服务器已连接';

      // 加入房间
      webRTCService.joinRoom(props.roomId, props.userId);

      // 生成分享链接
      const currentUrl = window.location.href.split('?')[0];
      roomLink.value = `${currentUrl}?room=${props.roomId}`;
    });

    webRTCService.on('connection-lost', () => {
      console.log('信令服务器连接已断开');
      connectionStatus.value = '连接已断开，尝试重新连接...';
      debugInfo.value += '\n信令服务器连接已断开';
    });

    webRTCService.on('track-added', ({ userId, stream }: { userId: string, stream: MediaStream }) => {
      console.log(`添加远程流: ${userId}`, stream);
      debugInfo.value += `\n接收到用户 ${userId} 的视频流`;

      // 更新远程流
      updateRemoteStream(userId, stream);
    });

    webRTCService.on('user-connected', (userId: string) => {
      console.log(`用户连接: ${userId}`);
      debugInfo.value += `\n用户 ${userId} 已连接`;

      // 仅当用户不是自己且不在列表中时添加
      if (userId !== props.userId && !roomUsers.value.includes(userId)) {
        const newUsers = [...roomUsers.value, userId];
        console.log('用户连接后更新用户列表:', newUsers);
        updateRoomUsers(newUsers);
      }
    });

    webRTCService.on('user-disconnected', (userId: string) => {
      console.log(`用户断开连接: ${userId}`);
      debugInfo.value += `\n用户 ${userId} 已断开连接`;

      // 从用户列表中移除
      const newUsers = roomUsers.value.filter(id => id !== userId);
      console.log('用户断开后更新用户列表:', newUsers);
      updateRoomUsers(newUsers);

      // 删除该用户的远程流
      removeRemoteStream(userId);
    });

    webRTCService.on('existing-users', (userIds: string[]) => {
      console.log('接收到现有用户列表:', userIds);
      debugInfo.value += `\n房间现有用户: ${userIds.join(', ')}`;

      if (Array.isArray(userIds)) {
        // 确保不包含当前用户ID并且没有重复项
        const uniqueUserIds = [...new Set(userIds.filter(id => id !== props.userId))];

        if (uniqueUserIds.length > 0) {
          console.log('更新用户列表为:', uniqueUserIds);
          updateRoomUsers(uniqueUserIds);
        }
      }
    });

    // 2. 初始化本地端
    // 获取本地媒体流
    debugInfo.value += '\n请求访问摄像头和麦克风...';
    localVideoLoading.value = true;

    const localStream = await webRTCService.getLocalStream({
      audio: true,
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 }
      } as MediaTrackConstraints
    });

    debugInfo.value += '\n成功获取本地媒体流';

    // 显示本地视频
    if (localVideoRef.value) {
      localVideoRef.value.srcObject = localStream;

      // 确保视频元素正确加载
      localVideoRef.value.onloadedmetadata = () => {
        console.log('本地视频元数据已加载');
        localVideoRef.value?.play().catch((e: any) => {
          console.error('自动播放本地视频失败:', e);
          debugInfo.value += '\n自动播放本地视频失败，请点击视频区域手动播放';
        });
      };

      // 添加本地视频事件监听
      localVideoRef.value.onplaying = () => {
        console.log('本地视频开始播放');
        localVideoLoading.value = false;
      };

      localVideoRef.value.onerror = () => {
        console.error('本地视频出错');
        localVideoLoading.value = false;
      };
    }

    // 添加对服务器信息和信令错误的监听
    webRTCService.on('server-info', (info: any) => {
      console.log('收到服务器信息:', info);
      debugInfo.value += `\n服务器信息: SocketID=${info.socketId}`;
    });

    webRTCService.on('signal-error', (error: { type: string, error: string }) => {
      console.error('收到信令错误:', error);
      debugInfo.value += `\n信令错误: ${error.type} - ${error.error}`;

      // 如果是用户未找到错误，说明用户列表可能有问题，尝试刷新
      // if (error.error === 'user-not-found') {
      //   console.log('尝试刷新用户列表...');
      //   if (webRTCService.socket && webRTCService.isConnected) {
      //     webRTCService.socket.emit('request-users', webRTCService.roomId);
      //   }
      // }
    });
  } catch (error: unknown) {
    console.error('初始化WebRTC失败:', error);
    errorMessage.value = `无法访问摄像头或麦克风: ${error instanceof Error ? error.message : String(error)}`;
    debugInfo.value += `\n错误: ${error instanceof Error ? error.message : String(error)}`;
    localVideoLoading.value = false;
  }
}

// 将视频元素与远程流关联
function setVideoElement(element: HTMLVideoElement | null, userId: string): void {
  console.log(`尝试设置远程视频元素 ${userId}`, element, remoteStreams.value[userId]);
  if (!element) {
    console.error(`视频元素为空: ${userId}`);
    updateVideoLoadingState(userId, 'error');
    return;
  }

  if (!remoteStreams.value[userId]) {
    console.error(`远程流不存在: ${userId}`);
    updateVideoLoadingState(userId, 'no-stream');
    return;
  }

  // 设置为加载中状态
  updateVideoLoadingState(userId, 'loading');

  try {
    // 先清除旧的视频源
    if (element.srcObject) {
      console.log(`重置视频元素 ${userId} 的srcObject`);
      element.srcObject = null;
    }

    // 设置新的视频源
    console.log(`设置远程视频元素 ${userId} 的srcObject`, remoteStreams.value[userId]);
    element.srcObject = remoteStreams.value[userId];

    // 确保视频元素正确加载
    element.onloadedmetadata = () => {
      console.log(`远程视频 ${userId} 元数据已加载，准备播放`);

      // 确保视频元素存在且未播放
      if (element && element.paused) {
        element.play().then(() => {
          console.log(`远程视频 ${userId} 播放成功`);
          debugInfo.value += `\n远程视频 ${userId} 播放成功`;
          updateVideoLoadingState(userId, 'playing');
        }).catch((e: unknown) => {
          console.error(`自动播放远程视频 ${userId} 失败:`, e);
          debugInfo.value += `\n自动播放远程视频 ${userId} 失败: ${e instanceof Error ? e.message : String(e)}`;
          updateVideoLoadingState(userId, 'autoplay-failed');
        });
      }
    };

    // 添加播放错误处理
    element.onerror = () => {
      console.error(`远程视频 ${userId} 出错`);
      debugInfo.value += `\n远程视频 ${userId} 出错`;
      updateVideoLoadingState(userId, 'error');
    };

    // 处理视频开始播放
    element.onplaying = () => {
      console.log(`远程视频 ${userId} 开始播放`);
      updateVideoLoadingState(userId, 'playing');
    };

    // 处理视频暂停
    element.onpause = () => {
      console.log(`远程视频 ${userId} 已暂停`);
      if (videoLoadingStates.value[userId] === 'playing') {
        updateVideoLoadingState(userId, 'paused');
      }
    };

    // 处理视频停止
    element.onstalled = () => {
      console.log(`远程视频 ${userId} 已停止`);
      updateVideoLoadingState(userId, 'stalled');
    };

  } catch (error: unknown) {
    console.error(`设置远程视频元素 ${userId} 失败:`, error);
    debugInfo.value += `\n设置远程视频元素 ${userId} 失败: ${error instanceof Error ? error.message : String(error)}`;
    updateVideoLoadingState(userId, 'error');
  }
}

// 离开房间
function leaveRoom(): void {
  console.log('离开房间');
  webRTCService.leaveRoom();
  emit('leave-room');
}

// 切换麦克风静音状态
function toggleMute(): void {
  if (webRTCService.localStream) {
    const audioTracks = webRTCService.localStream.getAudioTracks();
    if (audioTracks.length > 0) {
      const enabled = !audioTracks[0].enabled;
      audioTracks.forEach(track => {
        track.enabled = enabled;
      });
      isMuted.value = !enabled;
    }
  }
}

// 切换视频开关状态
function toggleVideo(): void {
  if (webRTCService.localStream) {
    const videoTracks = webRTCService.localStream.getVideoTracks();
    if (videoTracks.length > 0) {
      const enabled = !videoTracks[0].enabled;
      videoTracks.forEach(track => {
        track.enabled = enabled;
      });
      isVideoOff.value = !enabled;
    }
  }
}

// 复制房间链接到剪贴板
function copyRoomLink(): void {
  if (navigator.clipboard && roomLink.value) {
    navigator.clipboard.writeText(roomLink.value)
      .then(() => {
        alert('房间链接已复制到剪贴板');
      })
      .catch(err => {
        console.error('无法复制链接:', err);
      });
  }
}

// 强制更新远程视频流
function forceUpdateRemoteVideos(): void {
  console.log('强制更新所有远程视频流');
  debugInfo.value += '\n强制更新所有远程视频流...';

  // 获取所有远程视频元素并重新应用视频流
  roomUsers.value.forEach(userId => {
    const videoElement = document.getElementById(`video-${userId}`) as HTMLVideoElement;
    if (videoElement) {
      setVideoElement(videoElement, userId);
    } else {
      console.error(`找不到用户 ${userId} 的视频元素`);
      debugInfo.value += `\n找不到用户 ${userId} 的视频元素`;
    }
  });
}

// 刷新房间用户列表
function refreshUserList(): void {
  console.log('刷新房间用户列表');
  debugInfo.value += '\n手动刷新房间用户列表...';

  // 通过WebRTC服务重新请求房间用户列表
  if (webRTCService.socket && webRTCService.isConnected && webRTCService.roomId) {
    webRTCService.socket.emit('request-users', webRTCService.roomId);
    connectionStatus.value = '正在刷新用户列表...';

    // 同时尝试强制更新视频流
    forceUpdateRemoteVideos();

    // 在短暂延迟后恢复状态显示
    setTimeout(() => {
      if (connectionStatus.value === '正在刷新用户列表...') {
        connectionStatus.value = '已连接';
      }
    }, 2000);
  } else {
    debugInfo.value += '\n无法刷新用户列表：未连接到服务器或房间ID无效';
    errorMessage.value = '无法刷新用户列表：未连接到服务器';

    // 3秒后清除错误消息
    setTimeout(() => {
      if (errorMessage.value === '无法刷新用户列表：未连接到服务器') {
        errorMessage.value = '';
      }
    }, 3000);
  }
}

// 更新远程视频元素引用集合，用于管理视频元素
const remoteVideoRefs = ref<Record<string, HTMLVideoElement | null>>({});

// 在组件挂载时监听视频流变化
watch(remoteStreams, (newStreams, oldStreams) => {
  console.log('远程流发生变化，尝试更新视频元素');

  // 为新增的流设置视频元素
  Object.keys(newStreams).forEach(userId => {
    if (!oldStreams[userId] || newStreams[userId] !== oldStreams[userId]) {
      console.log(`检测到新的或更新的流: ${userId}`);

      // 在下一个DOM更新周期尝试设置视频元素
      nextTick(() => {
        const videoElement = document.getElementById(`video-${userId}`) as HTMLVideoElement;
        if (videoElement) {
          setVideoElement(videoElement, userId);
        }
      });
    }
  });
}, { deep: true });

// 在组件挂载时初始化WebRTC
onMounted(() => {
  console.log('VideoRoom组件已挂载');
  initializeWebRTC();
});

// 在组件卸载时清理资源
onBeforeUnmount(() => {
  console.log('VideoRoom组件将卸载');
  webRTCService.leaveRoom();
});
</script>

<template>
  <div class="video-room">
    <div class="room-header">
      <h2>房间: {{ roomId }}</h2>
      <p class="connection-status">状态: {{ connectionStatus }}</p>

      <div class="room-controls">
        <button @click="toggleMute" :class="{ active: isMuted }" class="control-btn">
          {{ isMuted ? '取消静音' : '静音' }}
        </button>

        <button @click="toggleVideo" :class="{ active: isVideoOff }" class="control-btn">
          {{ isVideoOff ? '开启视频' : '关闭视频' }}
        </button>

        <button @click="copyRoomLink" class="control-btn" title="复制房间链接">
          分享链接
        </button>

        <button @click="leaveRoom" class="leave-btn">离开房间</button>
      </div>
    </div>

    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>

    <div class="room-layout">
      <div class="video-container">
        <!-- 本地视频 -->
        <div class="video-item local-video">
          <video ref="localVideoRef" autoplay muted playsinline></video>
          <div class="video-label">
            {{ userId }} (我)
            <span v-if="isMuted" class="status-icon">🔇</span>
            <span v-if="isVideoOff" class="status-icon">🚫</span>
          </div>

          <!-- 本地视频加载状态 -->
          <div v-if="localVideoLoading" class="video-loading-overlay">
            <div class="loading-spinner"></div>
            <div class="loading-text">加载中...</div>
          </div>
        </div>

        <!-- 远程视频 -->
        <div v-for="remoteUserId in roomUsers" :key="remoteUserId" class="video-item remote-video">
          <video :id="`video-${remoteUserId}`" autoplay playsinline
            @loadedmetadata="console.log(`视频元数据已加载: ${remoteUserId}`)"
            @playing="updateVideoLoadingState(remoteUserId, 'playing')"
            @error="updateVideoLoadingState(remoteUserId, 'error')"></video>
          <div class="video-label">
            {{ remoteUserId }}
            <button
              @click="setVideoElement($event.target.closest('.remote-video').querySelector('video'), remoteUserId)"
              class="refresh-video-btn" title="刷新视频">
              🔄
            </button>
          </div>

          <!-- 远程视频加载状态 -->
          <div v-if="!videoLoadingStates[remoteUserId] || videoLoadingStates[remoteUserId] !== 'playing'"
            class="video-loading-overlay"
            :class="{ 'error': videoLoadingStates[remoteUserId] === 'error' || videoLoadingStates[remoteUserId] === 'no-stream' }">
            <div v-if="videoLoadingStates[remoteUserId] === 'loading'" class="loading-spinner"></div>
            <div class="loading-text">
              <template v-if="videoLoadingStates[remoteUserId] === 'loading'">视频加载中...</template>
              <template v-else-if="videoLoadingStates[remoteUserId] === 'error'">
                视频加载失败
                <div class="retry-btn"
                  @click="setVideoElement($event.target.closest('.remote-video').querySelector('video'), remoteUserId)">
                  点击重试
                </div>
              </template>
              <template v-else-if="videoLoadingStates[remoteUserId] === 'no-stream'">
                未接收到视频流
                <div class="retry-btn"
                  @click="setVideoElement($event.target.closest('.remote-video').querySelector('video'), remoteUserId)">
                  点击重试
                </div>
              </template>
              <template v-else-if="videoLoadingStates[remoteUserId] === 'autoplay-failed'">
                自动播放失败
                <div class="retry-btn"
                  @click="setVideoElement($event.target.closest('.remote-video').querySelector('video'), remoteUserId)">
                  点击播放
                </div>
              </template>
              <template v-else-if="videoLoadingStates[remoteUserId] === 'stalled'">
                视频已停止
                <div class="retry-btn"
                  @click="setVideoElement($event.target.closest('.remote-video').querySelector('video'), remoteUserId)">
                  点击重试
                </div>
              </template>
              <template v-else-if="videoLoadingStates[remoteUserId] === 'paused'">
                视频已暂停
                <div class="retry-btn"
                  @click="setVideoElement($event.target.closest('.remote-video').querySelector('video'), remoteUserId)">
                  点击播放
                </div>
              </template>
              <template v-else>等待连接...</template>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="users-panel">
        <div class="users-panel-header">
          <h3>房间用户 ({{ allUsers.length }})</h3>
          <div class="action-buttons">
            <button @click="forceUpdateRemoteVideos" class="action-btn" title="刷新所有视频">
              📹
            </button>
            <button @click="refreshUserList" class="refresh-btn" title="刷新用户列表">
              🔄
            </button>
          </div>
        </div>
        <ul class="users-list">
          <li v-for="user in allUsers" :key="user" :class="{ 'current-user': user === userId }">
            {{ user }} {{ user === userId ? '(我)' : '' }}
            <div class="user-status">
              <span v-if="user === userId && isMuted" class="status-badge muted">已静音</span>
              <span v-if="user === userId && isVideoOff" class="status-badge video-off">无视频</span>
              <span v-if="user !== userId" class="status-badge connected">已连接</span>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <div class="debug-panel">
      <details>
        <summary>调试信息</summary>
        <pre>{{ debugInfo }}</pre>
      </details>
    </div>
  </div>
</template>

<style scoped>
.video-room {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.room-header {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.room-controls {
  display: flex;
  gap: 10px;
  margin-top: 15px;
  flex-wrap: wrap;
}

.control-btn,
.leave-btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.2s;
}

.control-btn {
  background-color: #e9ecef;
  color: #495057;
}

.control-btn:hover {
  background-color: #dee2e6;
}

.control-btn.active {
  background-color: #fd7e14;
  color: white;
}

.leave-btn {
  background-color: #dc3545;
  color: white;
  margin-left: auto;
}

.leave-btn:hover {
  background-color: #c82333;
}

.connection-status {
  color: #6c757d;
  font-size: 14px;
  margin: 5px 0;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.room-layout {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.video-container {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.users-panel {
  width: 250px;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.users-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.users-panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.action-btn,
.refresh-btn {
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
  transition: all 0.2s;
}

.action-btn:hover,
.refresh-btn:hover {
  background-color: #e9ecef;
  transform: rotate(180deg);
}

.refresh-video-btn {
  background: none;
  border: none;
  color: white;
  font-size: 12px;
  cursor: pointer;
  padding: 0 5px;
  opacity: 0.7;
  transition: opacity 0.3s;
}

.refresh-video-btn:hover {
  opacity: 1;
}

.users-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 300px;
  overflow-y: auto;
}

.users-list li {
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 5px;
  background-color: #f8f9fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.users-list li.current-user {
  background-color: #e2f3ff;
  font-weight: bold;
}

.user-status {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.status-badge {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: normal;
}

.status-badge.connected {
  background-color: #28a745;
  color: white;
}

.status-badge.muted {
  background-color: #fd7e14;
  color: white;
}

.status-badge.video-off {
  background-color: #6c757d;
  color: white;
}

.video-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background-color: #000;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.local-video {
  width: 300px;
  height: 225px;
}

.remote-video {
  width: 300px;
  height: 225px;
}

video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5px 10px;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-icon {
  margin-left: 5px;
}

.debug-panel {
  margin-top: auto;
  padding-top: 15px;
  border-top: 1px solid #dee2e6;
}

details {
  color: #6c757d;
  font-size: 14px;
}

pre {
  white-space: pre-wrap;
  font-size: 12px;
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.video-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 2;
}

.video-loading-overlay.error {
  background-color: rgba(220, 53, 69, 0.6);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top: 4px solid #fff;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  color: white;
  font-size: 14px;
  text-align: center;
}

.retry-btn {
  margin-top: 8px;
  padding: 5px 10px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.retry-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

@media (max-width: 768px) {
  .room-layout {
    flex-direction: column;
  }

  .users-panel {
    width: 100%;
    order: -1;
  }

  .video-container {
    justify-content: center;
  }

  .local-video,
  .remote-video {
    width: 100%;
    max-width: 400px;
    height: auto;
    aspect-ratio: 4/3;
  }
}
</style>